<script setup>
import { ref, onUnmounted, toRefs } from 'vue'
import { getToken } from '@/utils/token'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import useImgPreview from '@/hooks/use-img-preview'

defineOptions({
  name: 'UploadSingleImg'
})

const modelValue = defineModel({type: String})

const props = defineProps({
  uploadTips: String,
  width: {
    type: String,
    default: '148px'
  },
  height: {
    type: String,
    default: '148px'
  },
  styleFlag: {
    type: Number,
    default: 0
  },
  isRead: Boolean
})
const emit = defineEmits(['on-success'])
const {width, height} = toRefs(props)

// 预览
const {actImg, visibleImgDialog, handlePreview} = useImgPreview()


const uploaderRef = ref()
const headers = {
  Authorization: getToken()
}
const disabled = ref(false)
// const action = `${import.meta.env.VITE_BASE_URL}/上传路径`
const action = '/mock/upload/image'
// 删除图片
const remove = () => {
  emit('update:modelValue', '')
  if (uploaderRef.value) {
    uploaderRef.value.clearFiles()
  }
  disabled.value = false
}

// 上传前
const beforeUpload = (file) => {
  disabled.value = true
  const imgTypes = ['image/jpeg', 'image/jpg', 'image/png']
  const fileType = file.type
  const isImg = imgTypes.includes(fileType)
  const isLt2M = file.size / 1024 / 1024 < 3

  if ( !isImg) {
    ElMessage.error('仅支持jpg/jpeg/png文件')
    return false
  }
  if ( !isLt2M) {
    ElMessage.error('上传图片不能超过 3MB!')
    return false
  }
  return isImg && isLt2M
}

// 上传成功
const onSuccess = (res) => {
  if (res.success) {
    emit('update:modelValue', res.data)
    emit('on-success')
  } else {
    ElMessage.error({message: '上传失败!'})
  }
}

onUnmounted(() => {
  if (modelValue.value) modelValue.value = ''
})
</script>
<template>
  <div class="upload-single-img">
    <template v-if="!isRead&&!modelValue">
      <ElUpload
          :class="['avatar-uploader',{'is-disabled':disabled}]"
          ref="uploaderRef"
          :action="action"
          :headers="headers"
          :limit="1"
          list-type="picture-card"
          :on-success="onSuccess"
          :before-upload="beforeUpload"
          :on-remove="remove"
      >
        <ElIcon class="avatar-uploader-icon">
          <Plus/>
        </ElIcon>
      </ElUpload>
    </template>
    <div class="image-preview-box" v-if="modelValue">
      <ElIcon class="del-shadow" @click="remove" v-if="!isRead">
        <Delete/>
      </ElIcon>
      <ElImage class="el-image-preview" fit="cover" :src="`${$fileUrl}${modelValue}`"
               @click="handlePreview(modelValue)" title="点击预览大图"/>
    </div>
    <ElDialog class="sing-img-preview-dialog" append-to-body align-center v-model="visibleImgDialog" width="720px">
      <ElImage fit="contain" :src="`${$fileUrl}${actImg}`"/>
    </ElDialog>
  </div>
</template>

<style lang="scss">
.upload-single-img {

  .el-upload {
    flex-direction: column;
    padding: var(--space-primary);


    &.el-upload--picture-card {
      width: v-bind(width);
      height: v-bind(height);
    }

    &.hide-uploader {
      display: none;
    }

    .el-icon {
      color: var(--color-primary);
      font-size: 3rem;
    }

    .upload-tips {
      @include font-grey;

    }

    p {
      text-align: justify;
      text-align-last: center;
      white-space: pre-line;
    }
  }

  .avatar-uploader {
    position: relative;

    &.is-disabled {
      .el-upload {
        position: absolute;
      }
    }
  }

  .image-preview-box {
    position: relative;
    width: v-bind(width);
    height: v-bind(height);
    border-radius: 4px;
    text-align: center;

    .el-image-preview {
      width: v-bind(width);
      height: auto;
    }

    .del-shadow {
      position: absolute;
      top: 4px;
      right: 0;
      width: 36px;
      height: 36px;
      line-height: 38px;
      color: #ffffff;
      font-size: 16px;
      z-index: 9;
      background: rgba(0, 0, 0, .4);
      cursor: pointer;
      display: none;
      border-radius: 4px;
    }

    &:hover {
      .del-shadow {
        display: block;

        &:hover {
          color: var(--color-danger);
        }
      }
    }
  }

}

.sing-img-preview-dialog {
  .el-dialog__header {
    height: 20px;
  }

  .el-image {
    width: 100%;

  }
}
</style>
